<template>
	<view class="aiStyle">
		<view>
			<!-- <u-notice-bar mode="horizontal" type="success" :list="listTop"></u-notice-bar> -->
			<u-top-tips ref="uTips" :type="success" :duration="duration"></u-top-tips>
		</view>

		<!-- {{sparkResult}} -->


		<!-- 文字部分 -->
		<view class="talkStyle" v-for="(item, index) in historyTextList" :key="index">

			<view class="talk" v-if="item.role=='user'">
				<view class="textStyle">{{item.content}}</view>
				<view class="myText-left">
					<u-avatar :src="avatar"></u-avatar>
				</view>
			</view>



			<view class="talk_ai" v-if="item.role=='assistant'">
				<view class="myText-right">
					<u-avatar :src="avatarAi"></u-avatar>
				</view>
				<view class="textStyle_ai">{{item.content}}</view>
			</view>

		</view>
		<view class="bg">
			<view class="bottomStyle">
				<view class="inputText">
					<u-input v-model="TEXT" :custom-style="inputStyle" border-color="1AAD19" placeholder="请输入需要AI回答的问题"
						:clearable="false" type="text" :focus="true" :height="height"
						:auto-height="autoHeight" @blur="blur_input"/>
				</view>
				<view style="margin-left: 1%;
    margin-right: 1%;
    align-items: center;
		    width: 19%;
    display: flex;"><u-button :custom-style="customStyle" class="logowz" style="color:#ffffff;" :type="btnType"
						@click="sendToSpark()" :loading="loadShow" :disabled="disabled">{{sendText}}</u-button></view>
			</view>

		</view>
	</view>
</template>

<script>
	import * as base64 from "base-64"
	import CryptoJS from '../../static/crypto-js/crypto-js.js'
	// import parser from '../../static/fast-xml-parser/src/parser'
	import * as utf8 from "utf8"
	export default {
		data() {
			return {
				btnType: "success",
				sendText: "发送",
				loadShow: false,
				customStyle: {
					// marginTop: '20px' // 注意驼峰命名，并且值必须用引号包括，因为这是对象
				},

				listTop: [
					''
				],
				avatar: "",
				avatarAi: "",
				textMy: "我",
				inputStyle: {
					backgroundColor: '#fff',
					margin: '0',
					width: "100%",

					color: "#000",
					paddingLeft: "5px",
					borderRadis: "50%",
				},
				placeholderStyle: {
					color: "#000"
				},
				height: 80,
				autoHeight: false,
				TEXT: '',
				APPID: '', // 控制台获取填写
				APISecret: '',
				APIKey: '',
				sparkResult: '',
				historyTextList: [{
					"role": "assistant",
					"content": "欢迎来到AI大模型！您可以提出您想问的问题，AI会替您一一解答！"
				}], // 历史会话信息，由于最大token12000,可以结合实际使用，进行移出
				tempRes: '', // 临时答复保存
				domain: "generalv2", //模型
				version: "v2.1", //版本
				talk: "",
				talkAi: "",
				talkList: [],
				disabled: false,
				count: 0
			}
		},

		onLoad() {
		},
		methods: {
			blur_input(){
				console.log("执行")
				uni.pageScrollTo({
				scrollTop: 0,
				duration: 0
				});
			},
			async sendToSpark() {
				if (this.TEXT.trim() != ""&&this.TEXT.trim() != null) {
					
					let myUrl = await this.getWebSocketUrl();
					this.loadShow = true;
					this.disabled = true;
					this.tempRes = "";
					this.sendText = "解答中";
					// this.sparkResult = "";
					let realThis = this;
					this.socketTask = uni.connectSocket({
						//url: encodeURI(encodeURI(myUrl).replace(/\+/g, '%2B')),
						url: myUrl,
						method: 'GET',
						success: res => {
							console.log(res, "ws成功连接...", myUrl)
							realThis.wsLiveFlag = true;
						}
					})
					realThis.socketTask.onError((res) => {
						console.log("连接发生错误，请检查appid是否填写", res)
					})
					realThis.socketTask.onOpen((res) => {
						this.historyTextList.push({
							"role": "user",
							"content": this.TEXT
						})
						// this.talkList.push({
						// 	"role": "user",
						// 	"content": this.TEXT
						// })
						console.info("wss的onOpen成功执行...", res)
						// 第一帧..........................................
						// console.log('open成功...')
						let params = {
							"header": {
								"app_id": this.APPID,
								"uid": "aef9f963-7"
							},
							"parameter": {
								"chat": {
									"domain": this.domain,
									"temperature": 0.5,
									"max_tokens": 1024
								}
							},
							"payload": {
								"message": {
									"text": this.historyTextList
								}
							}
						};
						console.log("请求的params：" + JSON.stringify(params))
						this.loadShow = true;
						// this.sparkResult =  this.TEXT;
						// this.talkList.push(this.sparkResult )
						this.sparkResult = this.sparkResult;
						// console.log("发送第一帧...", params)
						realThis.socketTask.send({ // 发送消息，，都用uni的官方版本
							data: JSON.stringify(params),
							success() {
								console.log('第一帧发送成功')
							}
						});
					});

					// 接受到消息时
					realThis.socketTask.onMessage((res) => {
						console.log('收到API返回的内容：', res.data);
						let obj = JSON.parse(res.data)
						// console.log("我打印的"+obj);
						let dataArray = obj.payload.choices.text;
						for (let i = 0; i < dataArray.length; i++) {
							realThis.sparkResult = realThis.sparkResult + dataArray[i].content
							realThis.tempRes = realThis.tempRes + dataArray[i].content

						}


						// this.talkAiList.push(this.sparkResult)
						// realThis.sparkResult =realThis.sparkResult+ 
						let temp = JSON.parse(res.data)
						// console.log("0726",temp.header.code)
						if (temp.header.code !== 0) {
							console.log(`${temp.header.code}:${temp.message}`);
							realThis.socketTask.close({
								success(res) {
									console.log('关闭成功', res)
									realThis.wsLiveFlag = false;
								},
								fail(err) {
									console.log('关闭失败', err)
								}
							})
						}
						if (temp.header.code === 0) {
							if (res.data && temp.header.status === 2) {
								let _this = this;
								this.loadShow = false;
								this.TEXT = "";
								this.disabled = false;
								this.sendText = "发送";
					
								realThis.sparkResult = realThis.sparkResult
								this.historyTextList.push({
									"role": "assistant",
									"content": this.tempRes
								})
								console.log("结束")
								/* let dataArray= obj.payload.choices.text;
								for(let i=0;i<dataArray.length;i++){
									realThis.sparkResult =realThis.sparkResult+ dataArray[i].content
								} */
								setTimeout(() => {
									realThis.socketTask.close({
										success(res) {
											console.log('关闭成功', res)
										},
										fail(err) {
											// console.log('关闭失败', err)
										}
									})
								}, 1000)
							}
						}
					})

				}
			},
			// 鉴权
			getWebSocketUrl() {
				return new Promise((resolve, reject) => {
					// https://spark-api.xf-yun.com/v1.1/chat  V1.5 domain general
					// https://spark-api.xf-yun.com/v2.1/chat  V2.0 domain generalv2
					var url = "wss://spark-api.xf-yun.com/" + this.version + "/chat";
					console.log(url)
					var host = "spark-api.xf-yun.com";
					var apiKeyName = "api_key";
					var date = new Date().toGMTString();
					var algorithm = "hmac-sha256";
					var headers = "host date request-line";
					var signatureOrigin = `host: ${host}\ndate: ${date}\nGET /` + this.version + `/chat HTTP/1.1`;
					console.log(signatureOrigin)
					var signatureSha = CryptoJS.HmacSHA256(signatureOrigin, this.APISecret);
					var signature = CryptoJS.enc.Base64.stringify(signatureSha);
					var authorizationOrigin =
						`${apiKeyName}="${this.APIKey}", algorithm="${algorithm}", headers="${headers}", signature="${signature}"`;
					var authorization = base64.encode(authorizationOrigin);
					url = `${url}?authorization=${authorization}&date=${encodeURI(date)}&host=${host}`;

					// console.log(url)
					resolve(url); // 主要是返回地址
				});
			},
		}
	}
</script>

<style>
	.aiStyle{
		display: flex;
		    flex-direction: column;
		    padding-bottom: 15%;
	}
	.bg {
		position: fixed;
		width: 100%;
		/* height: 100%; */
		bottom: 0;
		left: 0;
		z-index: 999;

	}

	page {
		position: relative;
		background-image: url("https://bpic.588ku.com/back_our/20201217/bg/89f905f39bc07.png");
		height: 100%;
		width: 100%;
		/* 背景图垂直、水平均居中 */
		background-position: center center;
		/* 背景图不平铺 */
		background-repeat: no-repeat;
		/* 当内容高度大于图片高度时，背景图像的位置相对于viewport固定 */
		background-attachment: fixed;
		/* 让背景图基于容器大小伸缩 */
		background-size: cover;
	}

	.bottomStyle {
		background: #f1f1f1;
		display: flex;
		align-items: center;
		justify-content: space-around;
		height: 70px;
	}

	.logowz {

		/* 	width: 100%;
		margin: 0 4% 0 0; */
	}

	.inputText {
		width: 73%;
		margin-left: 4%;
	}

	.myText-left {
		margin-left: 3%;

	}

	.myText-right {
		margin-right: 3%;

	}

	.talk {
		display: flex;
		align-items: center;
		margin: 5%;
		width: 90%;
		margin-left: 5%;
		justify-content: flex-end;
	}

	.talk_ai {
		display: flex;
		align-items: center;
		margin: 5%;
		width: 90%;
		margin-left: 5%;
		justify-content: start;
	}

	.talkStyle {
		height: 90%;
		width: 100%;
	}

	.textStyle {
		flex-wrap: wrap;
		ext-align: inherit;
		background: #fff;
		color: #000;
		padding: 10px;
		border-radius: 5%;
		word-wrap: break-word;
		/* 允许单词内断行 */
		white-space: normal;
		/* 处理空白符，自动换行 */
	}

	.textStyle_ai {
		word-wrap: break-word;
		/* 允许单词内断行 */
		white-space: normal;
		/* 处理空白符，自动换行 */
		flex-wrap: wrap;
		text-align: start;
		background: #6ccb7c;
		color: #fff;
		padding: 10px;
		border-radius: 5%;
	}
</style>